package com.ys.controller.api.storage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MenuId;
import com.ys.entity.storage.TccPreAllocatePublish;
import com.ys.entity.sys.YsCol;
import com.ys.service.storage.TccPreAllocatePublishService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 预约调拨发布单
 */
@Controller
@RequestMapping("/api/inter/tccPreAllocatePublish")
public class ApiInterTccPreAllocatePublishController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTccPreAllocatePublishController.class);

    @Autowired
    private CommonApiService<TccPreAllocatePublish> commonApiService;

    @Autowired
    private TccPreAllocatePublishService tccPreAllocatePublishService;

    //菜单id
    private Long menuId = MenuId.TCC_PreAllocatePublish;

    private String menuName = "预约调拨发布单";

    //权限字符
    private final String PERMISSIONS_VIEW = "tccPreAllocatePublish:view";
    private final String PERMISSIONS_ADD = "tccPreAllocatePublish:add";
    private final String PERMISSIONS_EDIT = "tccPreAllocatePublish:edit";
    private final String PERMISSIONS_STOP = "tccPreAllocatePublish:stop";

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TccPreAllocatePublish setSeachSql(TccPreAllocatePublish cond){

        cond

                .addLeftJoin("THR_OperateCompanyApply B ON B.Vgsbm = A.Vgsbm")//运营公司管理表
                .addField("B.Vgsjc AS vgsjc")//运营公司简称

                .addLeftJoin("TCC_Warehouse C ON C.Cck = A.WarehouseCode")//仓库表
                .addField("C.Vck AS vck")//仓库名称


                .addLeftJoin("TCC_PreAllocatePublishItem D ON D.Pbid = A.Bid")//子表
                .addField("D.Id AS sonId")//子表id
                //.addField("D.PublishVgsbm AS publishVgsbm")//发布公司编码
                .addField("D.PublishAmountByReality AS publishAmountByReality")//发布调拨价
                .addField("D.Status AS statusBySon")//启停用

                .addLeftJoin("THR_OperateCompanyApply E ON D.publishVgsbm = E.Vgsbm AND D.FromIsShow = 1")//运营公司管理表
                //.addField("E.Vgsjc AS publishVgsjc")//发布公司简称

                .addField("CASE WHEN D.PublishVgsbm IS NULL THEN 'all' ELSE D.PublishVgsbm END publishVgsbm")//发布公司编码
                .addField("CASE WHEN D.PublishVgsbm IS NULL THEN '所有' ELSE E.Vgsjc END publishVgsjc")//发布公司简称


                .addLeftJoin("TS_UserChange F on F.Id = A.CreateChangeId")
                .addField("F.UserId userId")


                //排序
        .setOrderby("A.Bid DESC");


        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TccPreAllocatePublish cond,String conditions
    ){
        try {
            cond = setSeachSql(cond);
            cond = commonApiService.dataAuth(menuId, cond);
            return commonApiService.searchLay(cond);
        }catch (Exception e){
            logger.error(menuName+"查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TccPreAllocatePublish cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = commonApiService.dataAuth(menuId, cond);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TccPreAllocatePublish> util = new ExportExcelUtils<>(new TccPreAllocatePublish());
            String toFilePath = util.exportExcel(listData, listField, menuName);
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error(menuName+"导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }



    /**
     * 新增
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toSave(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //新增
            return tccPreAllocatePublishService.add(params,menuId);
        } catch (Exception e) {
            logger.error(menuName+"新增出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 修改
     */
    @RequiresPermissions(PERMISSIONS_EDIT)
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //修改
            return tccPreAllocatePublishService.update(params,menuId);
        } catch (Exception e) {
            logger.error(menuName+"修改出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 删除
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/toDel")
    @ResponseBody
    public R toDel(Long id){
        try {
            return tccPreAllocatePublishService.del(id);
        } catch (Exception e) {
            logger.error(menuName+"出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }




    /**
     * 批量停用
     */
    @RequiresPermissions(PERMISSIONS_STOP)
    @RequestMapping("/stop")
    @ResponseBody
    public R stop(HttpServletRequest request, String choooseDatas){
        try {
            JSONArray detailJA = JSON.parseArray(choooseDatas);
            int doCount = 0;
            String resMsg = "";
            for (int i = 0; i < detailJA.size(); i++) {
                JSONObject detailJO = detailJA.getJSONObject(i);
                if(detailJO.get("sonId")!=null){
                    R res = tccPreAllocatePublishService.stop(Long.parseLong(detailJO.get("sonId").toString()));
                    if(res.getCode()==0){
                        doCount ++;
                    }else{
                        resMsg += (detailJO.get("bid")!=null?"单号："+detailJO.get("bid"):"")+"；"+res.getMsg()+"</br>";
                    }
                }else{
                    resMsg += (detailJO.get("bid")!=null?"单号："+detailJO.get("bid"):"")+"；不存在发布公司列表新增</br>";
                }
            }
            resMsg = "成功停用"+doCount+"条数据</br>"+resMsg;
            return R.ok(resMsg);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 预约挑拨单弹出框调用
     */
    @RequestMapping("/search2")
    @ResponseBody
    public LayuiTableVoJA search2(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TccPreAllocatePublish cond,String conditions,String publishVgsbm
    ){
        try {
            cond = setSeachSql(cond)
            .addField("A.PublishQuantity - A.AllocateQuantity mayDistributeNum,D.id preAllocatePublishItemId")
                    .where("D.Status = 1 AND (D.PublishVgsbm = '"+ publishVgsbm +"' OR D.PublishVgsbm IS NULL) AND (A.PublishQuantity - A.AllocateQuantity) >0");
            return commonApiService.searchLay(cond);
        }catch (Exception e){
            logger.error(menuName+"查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

}